﻿namespace Notes.Models;

internal class Note
{
    public Note()
    {
        Filename= $"{Path.GetRandomFileName()}.notes.txt";
        Date = DateTime.Now;
        Text = "";
    }
    public string Filename { get; set; }
    public string Text { get; set; }
    public DateTime Date { get; set; }

    public void Save() =>
        File.WriteAllText(Path.Combine(AppContext.BaseDirectory, Filename), Text);

    public void Delete() =>
        File.Delete(Path.Combine(AppContext.BaseDirectory, Filename));

    public static Note Load(string filename)
    {
        filename = Path.Combine(AppContext.BaseDirectory, filename);
        if (!File.Exists(filename))
        {
            throw new FileNotFoundException("Unable to find file on local storage.", filename);
        }

        return new Note
        {
            Filename = Path.GetFileName(filename),
            Text = File.ReadAllText(filename),
            Date = File.GetLastWriteTime(filename)
        };
    }

    public static IEnumerable<Note> LoadAll()
    {
        string appDataPath = AppContext.BaseDirectory;

        return Directory
            .EnumerateFiles(appDataPath, "*.notes.txt")
            .Select(filename => Note.Load(Path.GetFileName(filename)))
            .OrderByDescending(f => f.Date);
    }
}
